#include "../message-queue/src/client/Connection.hpp"
#include "compile_run.hpp"
#include <hiredis/hiredis.h>
#include <sw/redis++/redis++.h>
using namespace std;

void writeToRedisList(const string& key, const string& value)
{
    // 创建Redis客户端实例
    sw::redis::Redis redis("tcp://127.0.0.1:6379");

    // 向列表右侧添加一个值
    long long result = redis.rpush(key, value);
    
    if (result < 0) 
    {
        cerr << "Failed to push value to the list." << endl;
    }
}

// 把消息获取上来，进行编译后就应该加入到Redis中了
void cb(Channel::ptr &channel, const string consumer_tag, 
    const MessageQueue::BasicProperties *bp, const string &body)
{
    // 进行编译处理
    string out_json;
    if(!body.empty())
        CompileAndRun::Start(body, &out_json);
    Json::Value in_value;
    Json::Reader reader;
    reader.parse(body, in_value);
    string taskid = in_value["taskid"].asString();
    // 把结果加到Redis当中
    writeToRedisList(taskid, out_json);
    channel->basicAck(bp->id());
}

int main()
{

    //1. 实例化异步工作线程对象
    AsyncWorker::ptr awp = make_shared<AsyncWorker>();
    //2. 实例化连接对象
    Connection::ptr conn = make_shared<Connection>("127.0.0.1", 8085, awp);
    //3. 通过连接创建信道
    Channel::ptr channel = conn->openChannel();
    //4. 通过信道提供的服务完成所需
    //  1. 声明一个交换机exchange, 交换机类型为广播模式
    google::protobuf::Map<string, string> tmp_map;
    channel->declareExchange("exchange", MessageQueue::ExchangeType::TOPIC, true, false, tmp_map);
    //  2. 声明一个队列queue
    channel->declareQueue("queue", true, false, false, tmp_map);

    //  4. 绑定queue-exchange，且binding_key设置为queue
    channel->queueBind("exchange", "queue", "queue");

    auto functor = bind(cb, channel, placeholders::_1, placeholders::_2, placeholders::_3);
    channel->basicConsume("consumer1", "queue", false, functor);

    while(1) 
        this_thread::sleep_for(chrono::seconds(3));
    conn->closeChannel(channel);

    return 0;
}